package com.minosiants.dann.repository
import com.mongodb.casbah.MongoConnection

import com.mongodb.util.JSON
import com.minosiants.dann.repository.Gson._
import com.minosiants.dann.data.BasicData
import scala.collection.JavaConverters._
import com.mongodb.casbah.commons.conversions.scala._
import org.scala_tools.time.Imports._
import com.mongodb.DBObject
import com.mongodb.casbah.commons.MongoDBObject;import com.mongodb.casbah.Imports._;object MongoDataSource {
	 //val mongodbConfigPrefix = "akka.remote.server.server.client.storage.mongodb"
	 val hostName="127.0.0.1" //config.getString(mongodbConfigPrefix+".hostname", "127.0.0.1")
	 val dataBaseName = "dann" //config.getString(mongodbConfigPrefix+".dbname", "statistics")
	 val port =27017; //config.getInt(mongodbConfigPrefix+".port", 27017)	 lazy val mongo= MongoConnection(hostName,port)
	 def getDb()={
		 mongo(dataBaseName)
	 }
}

class MongoRepository() extends Repository{
	
	def findOne[T](qr:Query[T]):Option[BasicData]={
		collection(qr.collectionName).findOne(qr.queryObject).map(create(_,qr.clazz))
	};	
	def find[T](qr:Query[T]):List[BasicData]={
		collection(qr.collectionName).find(qr.queryObject).map(create(_,qr.clazz)).toList				
	};		private def create[T](o:DBObject,clazz:Class[T]):BasicData={		Gson().fromJson(toJson(o),clazz)	}
	def save(o:BasicData){
		val r=collection(o.collectionName).save(createDBObject(o))
	}  
	def delete(o:BasicData){
		collection(o.collectionName).remove(createDBObject(o))
	}
	def delete(id:String){
		//collection(collectionName(o.getClass)).remove()
	}	
	def drop(collectionName:String){		collection(collectionName).drop	}
	private def collection(name:String)={
		MongoDataSource.getDb()(name) 
	};	private def createDBObject(o:BasicData)={		JSON.parse(toJson(o)).asInstanceOf[DBObject];			}	
}